"""
REGCMD  #注册命令
REGSYS  #
QQ

"""

class BaseCmd(object):
    def __init__(self,user,kwargs):
        self.user = user
        self.kwargs = kwargs

@CmdManage.regcmd('#帮助')
class Help(BaseCmd):
    """帮助菜单"""
    def init(self,*args):
        h=[]
        for cmd,(func,type) in CmdManage.cmdlist.items():
            h.append("%s %s "%(cmd,func.__doc__))
        return '\n'.join(h)

@CmdManage.regcmd("#翻译")
class Fanyi(BaseCmd):
    """英汉互译 EG#翻译 HOW ARE YOU"""
    def init(self,*args):
        url="http://fanyi.youdao.com/openapi.do"
        data={"keyfrom":"suliunet",
              "key":"1784013593",
              "type":"data",
              "doctype":"json",
              "version":"1.1",
              "q":" ".join(args),
              }
        return eval(util.post(url,data))['translation'][0]

@CmdManage.regsys(r"(http[s]?://(?:[-a-zA-Z0-9_]+\.)+[a-zA-Z]+(?::\d+)"
                   "?(?:/[-a-zA-Z0-9_%./]+)*\??[-a-zA-Z0-9_&%=.]*)",
                   re.UNICODE)
class Gettitle(BaseCmd):
    def init(self,args):
        """获取网页标题"""
        url = args.group()
        tre = re.compile(b'<title[^>]*>([^<]*)<')
        content = b''
        title = b''
        try:
            with request.urlopen(url) as r:
                for i in range(100):
                    content += r.read(64)
                    if len(content) < 64:
                        break
                    m = tre.search(content, re.IGNORECASE)
                    n = re.compile('<meta\s+http-equiv="?content-type"?'
                                   '\s+content="?[^;]+;\s*charset=([^">]+'
                                   ')"?\s*/?>|<meta\s+charset="?([^">/"]+'
                                   ')"?\s*/?>', re.IGNORECASE)  #有些SB网站把charset写在后面
                    if m and n:
                        title = m.group(1)
                        break
        except Exception as e:
            return "出错了:%s"%e
        if content.upper().find(b'UTF-8') != -1:
            charset = 'utf-8'
        elif content.upper().find(b'GB2312') != -1 or content.upper().find(b'GBK'):
            charset = 'gbk'
        elif content.upper().find(b'BIG5') != -1:
            charset = 'big5'
        else:
            charset= 'utf-8'
        try:
            title = title.decode(charset).replace('\n', '')
            title = title.strip()
        except UnboundLocalError: #G.F.W
            title = 'G.F.W我恨你'
        return "网页标题:%s"%title if title else '特么的什么玩意竟然找不到标题'

class Pyshell(BaseCmd):
    def init(self,args):
        """执行代码 EG:#>>>print 's'*3 """
        url = "http://www.pythontip.com/coding/ajax_run"
        data= {'process':''.join(code)}
        header={'Referer':'http://www.pythontip.com/coding/run'}
        res = util.post(url,data,header)
        return res

#@CmdManage.regcmd("#关于")
class About(BaseCmd):
    """关于作者 """
    def init(self,*args):
        import time
        h=[]
        h.append("#codeby |道长且阻")
        h.append("#email  |ydhcui@suliu.net")
        h.append("#QQ     |664284092")
        h.append("#weibo  |http://weibo.com/ydhcui")
        h.append(time.strftime('%Y-%m-%d %X',time.localtime()))
        return '\n'.join(h)

@CmdManage.regcmd("#百度")
class Baidu(BaseCmd):
    """百科解释 EG#百度 python """
    def baike(self,url):
        res = request.urlopen(url).read().decode("utf-8")
        data= util.find(res,
              """<div class="card-summary-content"><div class="para">""",
              """</div></div></div>""")
        return util.html2str(data)
    def search(self,msg):
        url = 'http://www.baidu.com/s?wd=%s' %msg
        content = util.get(url)#.encode("utf-8")
        content = content.replace('\n','').replace('</table> <div','')
        res = ""
        for i in range(3):   #取3条结果
            temp = re.findall(r'(?<=id="\d").*?</table>|(?<=id="10").*?</table>',content)
            title = re.findall(r'<h3.*?<\/h3>',temp[i])
            title = re.compile('<.*?>').sub('',title[0])
            weburl = re.findall(r'(?<=href=").*?(?=")',temp[i])
            res += "%s%s\n"%(title,util.bddwz(weburl[0]))
            if "百度百科" in title:
                return baike(weburl[0])
        return res
    def init(self,*args):
        try:
            try:
                msg = parse.quote(' '.join(args))
                url = "http://baike.baidu.com/search/word?word=%s&pic=1&sug=1&enc=utf8" %msg
                return self.baike(url)
            except error.HTTPError as e:
                #不知为何手机上运行就不能自动跳转
                url = "http://baike.baidu.com/%s" %util.find(str(e),"url '/","' is")
                return self.baike(url)
        except: #改为百度搜索
                return self.search(parse.quote(''.join(args)))

@CmdManage.regcmd("#天气")
class Tianqi(BaseCmd):
    """查询天气 EG#天气 厦门 """
    def init(self,*args):
        url = "http://api.map.baidu.com/telematics/v3/weather?location=%s&output=json&ak=B122767f9cf32ad2c5a17d97835d053e"%parse.quote(args[0])
        res = json.loads(util.get(url))
        h=[]
        h.append(res['date'])
        for result in res['results']:
          h.append("%s  PM2.5:%s"%(result['currentCity'],result['pm25']))
          for data in result['weather_data']:
            h.append("%s %s %s %s"%(data['date'],data['weather'],data['wind'],data['temperature']))
        return '\n'.join(h)

#@CmdManage.regcmd("#快递")
class Kuaidi(BaseCmd):
    """快递查询 EG#快递 EMS 1075314674904"""
    def init(self,*args):
        return KUAIDI.main(args[0],args[1])

@CmdManage.regcmd("#笑话")
class Xiaohua(BaseCmd):
    """来个笑话  """
    def init(self,*args):
        id = random.choice(range(Joke.select().count()))
        res = Joke.get(Joke.id==id).data
        return res

@CmdManage.regcmd("#教学")
class Student(BaseCmd):
    """机器教学 EG#教学 你是谁 我是露露"""
    def init(self,*args):
        q,a = args[0],' '.join(args[1:])
        if len(q)<=100 and len(a)<=255:
           return CmdManage.ai.student(q,a)

#@CmdManage.regcmd("#种子")
class Btsearch(BaseCmd):
    def init(self,*args):
        '''种子搜索 EG#种子 关键字'''
        #http://www.tokyotosho.info/search.php?terms=%E4%B8%8A%E5%8E%9F&type=15
        msg = parse.quote('+'.join(args))
        url="https://btdigg.org/search?info_hash=&q=%s" % msg
        header={"Referer":"http://btdigg.org/search?info_hash=&q="}
        res=util.get(url,header=header)
        r=[]
        try:
            t=re.findall(r'<td class=\"idx\">.*?<pre class=\"snippet\">',res)
            for i in range(9):   #取3条结果
                d=re.findall(r'<a.*?href="(.*?)&amp;.*?>(.*?)<\/a>',t[i])
                r.append('\n'.join([d[0][1],d[1][0]]))
        except:
            if not r:r.append('没有找到%s的种子，试试别的关键词吧。'%''.join(args))
        finally:
            try:h=random.sample(r,3)
            except:h=r
            h.append('==============================')
            h.append('小撸怡情,大撸伤身,强撸灰飞烟灭。注意身体啊。骚年~')
        return '\n'.join(h)


#树莓派专用
@CmdManage.regcmd("#状态")
class GetRaspberry(BaseCmd):
  """主机状态"""
  def init(self,*args):
    """当前状态"""
    # Return CPU temperature as a character string
    def getCPUtemperature():
        res = os.popen('vcgencmd measure_temp').readline()
        return(res.replace("temp=","").replace("'C\n",""))
    # Return RAM information (unit=kb) in a list
    # Index 0: total RAM
    # Index 1: used RAM
    # Index 2: free RAM
    def getRAMinfo():
        p = os.popen('free')
        i = 0
        while 1:
            i = i + 1
            line = p.readline()
            if i==2:
                return(line.split()[1:4])
    # Return % of CPU used by user as a character string
    def getCPUuse():
        return(str(os.popen("top -n1 | awk '/Cpu\(s\):/ {print $2}'").readline().strip()))
    # Return information about disk space as a list (unit included)
    # Index 0: total disk space
    # Index 1: used disk space
    # Index 2: remaining disk space
    # Index 3: percentage of disk used
    def getDiskSpace():
        p = os.popen("df -h /")
        i = 0
        while 1:
            i = i +1
            line = p.readline()
            if i==2:
                return(line.split()[1:5])
    def getip():
        import socket
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.connect(("192.168.1.1",80))
        ipaddr=s.getsockname()[0]
        s.close()
        return ipaddr
    # CPU informatiom
    CPU_temp = getCPUtemperature()
    CPU_usage = getCPUuse()
    # RAM information
    # Output is in kb, here I convert it in Mb for readability
    RAM_stats = getRAMinfo()
    RAM_total = round(int(RAM_stats[0]) / 1000,1)
    RAM_used = round(int(RAM_stats[1]) / 1000,1)
    RAM_free = round(int(RAM_stats[2]) / 1000,1)

    # Disk information
    DISK_stats = getDiskSpace()
    DISK_total = DISK_stats[0]
    DISK_used = DISK_stats[1]
    DISK_perc = DISK_stats[3]
    list=[]
    list.append('CPU 温度 = '+CPU_temp+'度')
    list.append('CPU 占用 = '+CPU_usage+'%')
    list.append('RAM 总共 = '+str(RAM_total)+'MB')
    list.append('RAM 已用 = '+str(RAM_used)+'MB')
    list.append('RAM 空闲 = '+str(RAM_free)+'MB')
    list.append('ROM 总共 = '+str(DISK_total)+'B')
    list.append('ROM 已用 = '+str(DISK_used)+'B')
    list.append('ROM 比例 = '+str(DISK_perc))
    list.append('本机  IP = '+str(getip()))
    return '\n'.join(list)

@CmdManage.regcmd("#社工")
class GetQQGROUP(BaseCmd):
    """获取资料 EG#社工 QQ号"""
    def init(self,*args):
        g={}
        h=[]
        header = {'Referer':'http://qun.col.pw/'}
        url = "http://qun.col.pw/doquery.php?q=%s&type=1"%args[0]
        res = util.get(url,header)
        res = res.replace('\ufeff','')
        for line in res.split('\n'):
            try:
                info = line.split(',')
                g[info[0]] = info[2]
            except:pass
        if g:
            h.append('查到QQ:%s加入的群有'%args[0])
        else:
            return "木有找到QQ%s的相关信息"%args[0]
        for j,k in g.items():
            h.append("群号[%s] 昵称[%s]"%(j,k))
        return '\n'.join(h)


